<?php
/**
 * Cache
 * @filesource
 */
/**
 * Namespace
 */
namespace framework\library;
/**
 * Dependencies
 */
use framework\library\interfaces\Cache_Interface;
/**
 * Cache Class
 *
 * A file based cache implementation
 *
 * @author Randy Casburn <randy@plurious.com>
 * @copyright Copyright Plurious Software, all rights reserved
 * @license MIT
 * @license http://www.opensource.org/licenses/mit-license.html
 * @link http://plurious.com/framework/documentation/classes/Front.html
 * @version 2.1
 */
class Cache implements Cache_Interface {

    /** holds expiration timeframe */
    private $expire = 3600;

    public function __construct() {
        $this->freshen();
    }

    /**
     * Clear out old/stale cache files
     */
    public function freshen() {
        $files = glob(CACHE_DIR . 'cache.*');

        if ($files) {
            foreach ($files as $file) {
                $time = substr(strrchr($file, '.'), 1);
                $currTime = time();
                if ($time < time()) {
                    if (file_exists($file)) {
                        unlink($file);
                        clearstatcache();
                    }
                }
            }
        }
    }

    /**
     * Retrieve cached data based up on a key lookup
     * 
     * @param string $key magic number used for cache identity
     * @return string the cache content  
     */
    public function get($key) {
        $files = glob(CACHE_DIR . 'cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key) . '.*');
        if ($files) {
            $cache = file_get_contents($files[0]);
            return unserialize($cache);
        }
        return false;
    }

    /**
     * Store data in the cache 
     * 
     * Store as key with content being value
     * 
     * @param string $key
     * @param string $value 
     */
    public function set($key, $value) {
        $this->delete($key);
        $file = CACHE_DIR . 'cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key) . '.' . (time() + $this->expire);
        file_put_contents($file, serialize($value));
    }

    /**
     * Remove cached data by removing the file holding the cache
     * 
     * @param string $key 
     */
    public function delete($key) {
        $files = glob(CACHE_DIR . 'cache.' . preg_replace('/[^A-Z0-9\._-]/i', '', $key) . '.*');
        if ($files) {
            foreach ($files as $file) {
                if (file_exists($file)) {
                    unlink($file);
                    clearstatcache();
                }
            }
        }
    }

    /**
     * Clear all cached data
     */
    public function clear() {
        $files = glob(CACHE_DIR . 'cache.*');

        if ($files) {
            foreach ($files as $file) {
                unlink($file);
                clearstatcache();
            }
        }
    }

}

?>